const Router = require("koa-router")
const {successRender, errorRender} = require('../utils/utils')
const router = new Router()
const {proving} = require('../utils/token')
const Carousel = require('../model/Carousel')
const Menu = require('../model/Menu')

//查询轮播图
router.get('/getCarousel', async ctx => {
  const res = await Carousel.find()
  ctx.body = successRender({data: res})
})

//添加轮播图
router.post('/addCarousel', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  if (userId) {
    const info = ctx.request.body
    const res = await new Carousel(info).save()
    ctx.body = successRender({msg: '添加成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//删除轮播图
router.get('/deleteCarousel', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  if (userId) {
    const _id = ctx.request.query.id
    const res = await Carousel.findOneAndRemove({_id})
    ctx.body = successRender({msg: '删除成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//查询推荐
router.get('/getRecommend', async ctx => {
  const res = await Menu.find({recommend: true})
  ctx.body = successRender({data: res})
})

module.exports = router
